Summary of commonly used JavaScript techniques for improving performance [Classic]

  • 2021-06-29 09:48:13
  • OfStack

This article describes the common techniques JavaScript uses to improve performance.Share it for your reference, as follows:

1. Attention Scope

As the number of scopes in the scope chain increases, the time to access variables outside the current scope also increases. Accessing global variables is always slower than accessing local variables, because the scope chain is traversed.
1). It is always correct to avoid global lookups to store global objects that are used multiple times in a function as local variables.

2). Avoiding the with statement with will create its own scope, thereby increasing the length of the scope chain in which the code is executed.

2. Choose the right method

Part of the performance problem is related to the algorithm or method used to solve the problem.

1). Avoid unnecessary attribute lookups

In computer science, the complexity of an algorithm is represented by the O symbol. The simplest and fastest algorithm is the constant value, O(1). After that, the algorithm becomes more complex and takes longer to execute. The common types of JavaScript algorithms are:

Constant: No matter how many values there are, the execution time is constant. 1 generally represents simple values and values stored in variables.

Logarithm: The total execution time is related to the number of values, but it is not necessary to get each value to complete the algorithm. For example: 2-point lookup

Linear: The total execution time is directly related to the number of values. For example, traverse all elements in an array

Square: The total execution time is related to the number of values, each value must obtain at least n times. For example: insert sort

Cube: The total execution time is related to the number of values, each of which takes at least the square of n

Using variables and arrays is more efficient than accessing attributes on objects. Finding any attribute on an object takes longer than accessing variables or arrays because the attribute with that name must be searched once in the prototype chain.

1 Generally speaking, as long as the complexity of the algorithm is reduced, try to minimize it.Replace attribute lookup with value lookup as much as possible using local variables.In step 1, if you can access it from a digitized array location, you can also use named attributes (such as an NodeList object), then use array location.

2). Optimizing cycle

a.Impairment iteration In many cases, iterators that continuously decrease values in a loop are more efficient starting with the maximum value.
b.Simplified termination condition Since the termination condition is calculated for each cycle, it must be guaranteed to be as fast as possible.
c.Simplifying the circulatory body is the most executed, so make sure it is optimized to the maximum.Make sure there are no intensive calculations that can be easily removed from the cycle.
d. The most commonly used for and while loops for post-use test loops are pre-test loops. Post-test loops, such as do-while, avoid the calculation of initial termination conditions and are therefore faster.

3. Expand loops When the number of loops is determined, it is often faster to eliminate loops and use multiple function calls, such as the well-known Duff device

4). Avoid double interpretation

There is a double-interpreted penalty when the JavaScript code wants to parse JavaScript. For example:


eval("alert('Hello world!')");
// Some code evaluations 

Amendment:


alert('Hello world');


var sayHi = new Function("alert('Hello world!')");   

Amendment:


var sayHi = function(){
  alert("Hellow world!');
};


setTimeout("alert('Hellow world!')",500);

Amendment:


setTimeout(function)({
   alert('Hellow world!');
},500);

5). Other methods

Native methods are faster -- rewrite one using native methods instead of JavaScript, whenever possible. Native methods are written in compiled languages such as C/C++, so much faster than JavaScript. The easiest thing to forget about in JavaScript is the complex mathematical operations that can be found in the Math object;These methods are much faster than any of the same methods written in JavaScript, such as sine and cosine.

Switch statements are faster -- if you have a complex set of if-else statements, you can convert them to a single switch statement for faster code. You can also optimize the switch statement one step by organizing the case statements in the order that is most likely to be least likely.

Bit operators are faster--when performing mathematical operations, bitwise operations are faster than any Boolean or arithmetic operation.Selective bitwise operations can greatly improve the performance of complex calculations.For example, modulus, logic and logic, or bitwise operations can be considered to replace them.

3. Minimize the number of statements

1). Multiple variable declarations

For example:


//4 Statement --- Waste 
var count = 5;
var color = "blue";
var values = [1,2,3];
var now = new Date();

Optimize:


var count = 5,
color = "blue", 
values = [1,2,3],
noiw = new Date();

In most cases, this optimization is very easy to do and much faster than declaring individual variables separately.

2). Insert Iteration Value

For example:


var name = values[i];
i++;

Optimize:


var name = values[i++];

3). Use arrays and object literals

For example:

var values = new Array(); --- > var values = [];
var obj = new Object(); --- > var obj = {};

4. Optimize DOM interaction

1). Minimize on-site updates

1Once you need to visit the DOM section as part of the already displayed page, you are doing a live update. The reason for this is that the page needs to be updated immediately (live) to the user's display. Whether inserting a single character or removing the entire fragment, there is a performance penalty because the browser recalculates an infinite number of sizes to update.

Example:


alert('Hello world');

0

This adds 10 items, a total of 20 on-site updates. The following improvements are made by creating document fragments:


alert('Hello world');

1

In this example, there is only one on-site update, which happens after all the items have been created. Document fragmentation is used as a temporary placeholder to place the newly created items. Then all items are added to the list using appendChild (). Remember, when appendChild () is passed in to document fragmentation, only the child nodes in the fragmentation are added to the target, and the fragmentation itself is not added.

1Once you need to update DOM, consider using document fragmentation to build the DOM structure and then add it to an existing document.

2). Use innerHTML

There are two ways to create an DOM node on a page: using DOM methods such as createElement (), appendChild (), and using innerHTML for small DOM changes is almost as efficient. For large DOM changes, using innerHTML is much faster than using the standard DOM method to create the same DOM structure.Using innerHTML once is considerably faster than using innerHTML multiple times.

3. Use event proxy (brief, omitted)

4). Note NodeList

Minimizing the number of visits to NodeList can greatly improve script performance.

The NodeList object is returned when:

a.A call to getElementsByTagName() was made
b.Gets the element's childNodes attribute
c.Gets the element's attributes attribute
d. accessed special collections such as document.forms, document.images, and so on

Understand that when using the NodeList object, proper use can greatly speed up code execution.

The function throttling described earlier is also an important aspect.This method is useful especially for multiple loops, which can be time consuming.

PS: Compressing javascript and reducing code volume are also effective ways to improve javascript performance.Here are two very useful compression tools:

JavaScript Compression/Format/Encryption Tool:
http://tools.ofstack.com/code/jscompress

jsmin Online js Compression Tool:
http://tools.ofstack.com/code/jsmincompress

More readers interested in JavaScript related content can view this site's topics: JavaScript Switching Special Effects and Techniques Summary, JavaScript Finding Algorithmic Techniques Summary, JavaScript Animation Special Effects and Techniques Summary, JavaScript Errors and Debugging Techniques Summary, JavaScript Data Structure and Algorithmic Techniques Summary, and so on.Summary of JavaScript Traversal Algorithms and Techniques and Summary of JavaScript Mathematical Operation Usage

I hope that the description in this paper will be helpful to everyone's JavaScript program design.


Related articles: